<template>
  <view class="content">
    <img v-if="config" class="bg-img" :src="config.configJson.config.index.bgImg" />
    <image class="top-logo" src="@/static/image/top-logo.png"></image>

    <view v-if="activeConfig" class="top-title-info">
      <text class="title">集齐财神 拼手气分万元大奖</text>
      <text class="info">
        {{ activeConfig.gatherMan }}人已集齐，{{
          dateUtil(activeConfig.openTime).format('YYYY年M月D日H点')
        }}开奖
      </text>
    </view>

    <!-- 活动规则按钮 -->
    <view
      style="
        position: absolute;
        top: 200rpx;
        right: 50%;
        width: 180rpx;
        height: 44rpx;
        margin: 0 auto;
        transform: translateX(50%);
        text-align: center;
        border-radius: 12rpx;
        color: #702a00;
        cursor: pointer;
      "
      @click="$refs.ruleRef.open()"
    >
      <image
        style="width: 100%; height: 100%; position: absolute; top: 0; left: 0"
        src="https://wxlsrecode2.oss-cn-shanghai.aliyuncs.com/lottery_model/2024-01-30/18f63d64-5cf4-4710-83d2-563e21c14c92.png"
      >
      </image>
    </view>

    <!-- 翻转卡牌 -->
    <div class="flip_wrap" :style="cssVars">
      <div
        v-if="!isLotteryDraw"
        class="flip"
        :class="cardActive && 'flip-active'"
        @click="cardClick()"
      >
        <div class="side front">
          <image class="logo" :src="frontImg"></image>
        </div>
        <div class="side back">
          <image class="logo" :src="backImg" @load="backImgLoadEvent"></image>
        </div>

        <!-- 翻转时移动的图片 -->
        <view
          v-show="translate.show"
          class="translate-img"
          :class="translate.show && 'translate-active'"
        >
          <image class="logo" :src="translate.translateImg"></image>
        </view>
      </div>

      <view v-if="config && isLotteryDraw" class="lottery-draw-flip">
        <!-- 开奖后的展示 -->
        <image class="logo" :src="config.configJson.config.index.lotteryDrawFlip"></image>
        <view class="lottery-draw-text">
          <text v-if="my.prize.length > 0">
            恭喜您，中奖啦！<br />获得{{ my.prize[0].prizeName.split('：')[0] }}
          </text>
          <text v-else>很遗憾，您未中奖！</text>
        </view>
        <view class="lottery-draw-btn" @click="viewWinners()">
          <image
            style=""
            src="https://wxlsrecode2.oss-cn-shanghai.aliyuncs.com/lottery_model/2024-01-30/6c86272c-bdcf-43fe-97c1-46f033ca0e6f.png"
            mode="widthFix"
          >
          </image>
        </view>
      </view>

      <!-- 点击我的卡片预览卡片信息 -->
      <view v-show="my.viewImg" class="lottery-draw-flip" style="position: absolute; top: 0">
        <image class="logo" :src="my.viewImg"></image>
      </view>
    </div>
    <!-- 翻转卡牌 END -->

    <!-- 翻卡次数提示 -->
    <view class="card-num">
      <text> 今日您有{{ my.getCardNum }}次获取卡牌的机会 </text>
      <!-- <text v-else>今日您获取卡牌机会已用完，请明日再来！</text> -->
    </view>

    <!-- 卡片列表 -->
    <scroll-view
      scroll-x
      class="card-wrap"
      :scroll-into-view="scrollIntoView"
      @touchmove.stop="noAct"
    >
      <view class="card-content">
        <view
          class="card-item"
          :class="`${canCompound && index === 0 && !isLotteryDraw ? 'buttonAnimate' : ''}`"
          v-for="(item, index) in card.list"
          :key="index"
          :id="`item${item.id}`"
        >
          <!-- index === 0 的是合成按钮 -->
          <image
            v-if="(index === 0 && !isLotteryDraw) || index > 0"
            class="card-item-img"
            :class="`
              ${
                ((!canCompound && index === 0 && item.num === 0) ||
                  (index > 0 && item.num === 0)) &&
                'filter-grayscale-40'
              }
            `"
            :style="((canCompound && index === 0) || (index > 0 && item.num > 0)) && 'opacity: 1;'"
            :src="item.image"
            @click="index === 0 ? compoundClick() : myCardClick(item)"
          ></image>
          <!-- 已开奖 -->
          <image
            v-if="index === 0 && isLotteryDraw"
            class="card-item-img"
            src="https://wxlsrecode2.oss-cn-shanghai.aliyuncs.com/lottery_model/2024-01-30/a32702aa-e7cd-4b22-b950-9af6505b75f1.jpg"
          ></image>

          <view v-if="item.num > 0" class="num-tag box-shadow">{{ item.num }}</view>

          <view
            v-if="index > 0 && card.compound"
            class="compound-img-box"
            :style="card.translateX && `transform: translateX(-${index * 226}rpx)`"
          >
            <!-- 合成时移动的图片 -->
            <!-- :style="card.compound && `animation: bounceOutDown1 1000;`" -->
            <image class="compound-img" :src="item.image"></image>
          </view>

          <!-- 预览背景 -->
          <view v-if="item.id === my.viewId" class="view-bg"></view>
        </view>
      </view>
    </scroll-view>
    <!-- 卡片列表 END -->

    <!-- 已开奖 -->
    <view v-if="isLotteryDraw" class="lottery-draw-tip">
      <image
        v-if="config"
        class="my-card-btn"
        :src="config.configJson.config.myCard.image"
        :style="config.configJson.config.myCard.imageStyle"
        mode="widthFix"
        @click="toMyCard"
      >
      </image>
    </view>

    <view style="height: 100rpx"></view>

    <!-- 规则 -->
    <rule v-if="config" ref="ruleRef" :id="config.configJson.config.rule.id" top="20%"></rule>

    <!-- 阅读任务前置 -->
    <readTask
      v-if="config"
      ref="readTaskRef"
      :buzId="config.code"
      :isMaskClick="true"
      @close="toReadTask"
    ></readTask>

    <!-- 转盘抽奖 -->
    <lotteryGridComp ref="lotteryGridCompRef" :isOpenAddLotteryCount="false"></lotteryGridComp>

    <!-- 中奖名单 -->
    <winngersComp ref="winngersCompRef"></winngersComp>

    <!-- 我的奖品 -->
    <my-prize
      v-if="config"
      ref="myPrizeRef"
      style="position: fixed; top: 52%; right: -6rpx; z-index: 9"
      :jobId="config.configJson.lottery.id"
    ></my-prize>
    <!-- 我的奖品 END -->

    <!-- 加载组件 -->
    <loading v-show="!isRender" style="z-index: 991"></loading>
  </view>
</template>

<script>
  import { mapGetters } from 'vuex';
  import * as Api from '@/server/index.js';
  import * as Utils from '@/utils/index.js';
  import { dateUtil } from '@/utils/dateUtil.js';
  import rule from '@/components/rule/index.vue';
  import readTask from '@/components/readTask/index.vue';
  import lotteryGridComp from '@/components/lotteryWheelComp/index.vue';
  import myPrize from '@/components/lotteryWheelComp/components/myPrize/myPrize.vue';
  import winngersComp from './components/winngersComp/index.vue';

  const isUniapp = Utils.util.isUniapp();

  export default {
    components: {
      rule,
      readTask,
      lotteryGridComp,
      myPrize,
      winngersComp,
    },

    data() {
      return {
        options: null,
        isRender: '',
        dateUtil: dateUtil,
        activeConfig: null,
        cardActive: false,
        frontImg:
          'https://wxlsrecode2.oss-cn-shanghai.aliyuncs.com/lottery_model/2024-01-29/510b39ef-e53a-4750-a1da-8ff2fe2b5462.jpg',
        backImg: '',
        backCardId: '',
        translate: {
          show: false,
          translateImg: '',
          translateTime: 2000,
        },
        imgurl: require('@/static/logo-back.png'),

        card: {
          compound: false,
          translateX: false,
          translateTime: 2000,
          list: [],
        },
        my: {
          cards: [], // 当前有的卡
          compositeCard: 0, // 合成卡的数量
          getCardNum: 0, // 获取卡的次数
          prize: [], // 定时开奖的奖品
          viewId: '',
          viewImg: '',
        },
        scrollIntoView: '',
      };
    },
    computed: {
      ...mapGetters(['token', 'config']),
      cssVars() {
        return {
          '--translateTime': this.translate.translateTime / 1000 + 's',
          '--compoundImgTranslate': (index) => {
            return index * 200 + 'rpx';
          },
        };
      },
      /**
       * 是否能合成
       */
      canCompound() {
        return this.card.list.slice(1).every((item) => item.num > 0);
      },

      /**
       * 是否已开奖
       */
      isLotteryDraw() {
        // return true; // TODO
        return this.activeConfig ? dateUtil() > dateUtil(this.activeConfig.openTime) : false;
      },
    },

    async onLoad(options) {
      // 获取acctoken
      this.options = options;
      await this.$onLaunched;
      try {
        uni.setNavigationBarTitle({
          title: this.$store.getters.config.pageTitle,
        });
      } catch (e) {}

      await this.initLoad(); //数据初始化
      this.init_load();
    },

    onShow() {
      if (window.h5uni && this.isRender) {
        h5uni.postMessage({
          data: {
            share: this.share,
          },
        });
      }
    },

    // 监听用户下拉动作，一般用于下拉刷新
    async onPullDownRefresh() {
      await this.init_load(); //数据初始化
      const timer = setTimeout(function () {
        clearTimeout(timer);
        uni.stopPullDownRefresh();
      }, 100);
    },

    methods: {
      async init_load() {
        await this.getActiveConfig();
        await this.getCardType();

        if (this.isLotteryDraw) this.getSelfPrize();

        const checkLogin = this.checkLogin();
        if (!checkLogin) return;

        this.getMyCard();
        this.getFlipSum();

        Utils.util.setTimeoutFunc(() => {
          this.isRender = true;
        }, 500);
      },

      /**
       * 已经集齐卡人数和开奖时间
       */
      async getActiveConfig() {
        Utils.Msg.ShowLoading();
        try {
          const { data: res } = await Api.index.getConfig();
          Utils.Msg.HideLoading();
          this.activeConfig = res.data;
        } catch (error) {
          Utils.Msg.HideLoading();
        }
      },

      /**
       * 自己的定时开奖中奖奖品
       */
      async getSelfPrize() {
        Utils.Msg.ShowLoading();
        try {
          const { data: res } = await Api.index.selfPrize();
          Utils.Msg.HideLoading();
          this.my.prize = res.data;
          this.$store.commit('setSelfPrize', res.data);
        } catch (error) {
          Utils.Msg.HideLoading();
        }
      },

      /**
       * 获取全部卡种
       */
      async getCardType() {
        Utils.Msg.ShowLoading();
        try {
          const { data: res } = await Api.index.getCardType();
          Utils.Msg.HideLoading();

          const list = this.config.configJson.config.card.list;
          const cardList = list.map((item) => {
            const index = res.data.findIndex((el) => el.id == item.id);

            return index >= 0
              ? {
                  ...res.data[index],
                  ...item,
                }
              : item;
          });
          this.card.list = cardList;
        } catch (error) {
          Utils.Msg.HideLoading();
        }
      },

      /**
       * 获取我的卡片
       */
      async getMyCard() {
        Utils.Msg.ShowLoading();
        try {
          const { data: res } = await Api.index.getCard();
          Utils.Msg.HideLoading();
          /* {
            "cards": [
              {
                "cardType": 0, // 卡类型（对应卡类型id）
                "sum": 0 // 当前有的数量
              }
            ],
            "compositeCard": 0 // 已合成卡数量
          } */
          this.my.cards = res.data.cards;
          this.my.compositeCard = res.data.compositeCard;
          this.card.list[0].num = res.data.compositeCard;
          res.data.cards.forEach((item) => {
            const index = this.card.list.findIndex((el) => el.id === item.cardType);
            if (index >= 0) {
              this.card.list[index].num = item.sum;
            }
          });
        } catch (error) {
          Utils.Msg.HideLoading();
        }
      },

      /**
       * 查询本日还可翻卡次数
       */
      async getFlipSum() {
        Utils.Msg.ShowLoading();
        try {
          const { data: res } = await Api.index.getFlipSum();
          Utils.Msg.HideLoading();
          this.my.getCardNum = res.data;
          // this.my.getCardNum = 1; //TODO
        } catch (error) {
          Utils.Msg.HideLoading();
        }
      },

      /**
       * 卡片点击
       */
      cardClick() {
        if (this.cardClickMask) return;
        if (this.cardActive) {
          // 领取
          this.getCard();
        } else {
          if (this.my.getCardNum === 1 && !this.$refs.readTaskRef.isAllRead) {
            // 剩余一次翻卡机会且还未阅读，去阅读
            this.$refs.readTaskRef.open();
            return;
          }
          // 开卡
          this.open();
        }
      },

      /**
       * 点击我的卡片预览
       */
      myCardClick(item) {
        // if (this.my.getCardNum > 0) return;
        if (this.my.viewId === item.id) {
          this.my.viewId = '';
          this.my.viewImg = '';
          return;
        }
        this.my.viewId = item.id;
        this.my.viewImg = item.image;
      },

      /**
       * 翻卡
       */
      async open() {
        this.cardClickMask = true;
        // Utils.Msg.ShowLoading();
        try {
          const { data: res } = await Api.index.flipCard({ time: new Date().getTime() });
          // Utils.Msg.HideLoading();
          /* const res = {  // 测试数据
            data: {
              id: 6,
              isAlive: 1,
              createBy: 60065,
              cardType: 2,
              createTime: '2024-01-30 16:56:57',
              updateBy: null,
              updateTime: '2024-01-30 16:56:57',
              compositeCard: null,
              mobile: '13282573720',
            },
          }; */
          this.backCardId = res.data.cardType;
          this.card.list.forEach((item) => {
            if (item.id == res.data.cardType) {
              this.backImg = item.bigImage;
              this.translate.translateImg = item.bigImage;
            }
          });
          // console.log('翻卡 :>> ', res.data);
          if (this.my.getCardNum === 2) await this.$refs.lotteryGridCompRef.setRoster();
          if (this.my.getCardNum === 1) await this.$refs.lotteryGridCompRef.toGetLotteryNum(false);

          this.my.getCardNum--;
          const timer = setTimeout(() => {
            clearTimeout(timer);
            this.cardClickMask = false;
          }, 600);
        } catch (error) {
          // Utils.Msg.HideLoading();
          this.cardClickMask = false;
        }
      },
      /**
       * 当图片载入完毕时
       * @param {*} e
       */
      backImgLoadEvent(e) {
        this.cardActive = true;
        uni.hideLoading();
      },
      /**
       * 领取
       */
      async getCard() {
        this.cardClickMask = true;
        this.translate.show = true;
        this.scrollIntoView = 'item' + this.backCardId;
        const timer = setTimeout(() => {
          clearTimeout(timer);
          this.translate.show = false;
          this.cardActive = false;

          // 卡片数量增加
          this.card.list.forEach((item) => {
            if (item.id == this.backCardId) {
              item.num++;
            }
          });

          const timer1 = setTimeout(() => {
            clearTimeout(timer1);
            this.cardClickMask = false;
            this.backImg = '';
            this.backCardId = '';
            this.scrollIntoView = '';
            this.translate.translateImg = '';

            const hasLotteryCoun =
              this.$refs.lotteryGridCompRef.job.info.drawType === 1
                ? this.$refs.lotteryGridCompRef.myLottery.info.canLimit
                : this.$refs.lotteryGridCompRef.myLottery.info.lotteryCount;
            if (hasLotteryCoun > 0) this.$refs.lotteryGridCompRef.open(); // 有抽奖次数弹出抽奖
          }, 1000);
        }, 1000);
      },

      /**
       * 查看中奖名单
       */
      viewWinners() {
        this.$refs.winngersCompRef.openComp();
      },

      /*****************************************/

      /**
       * 合成
       */
      async compoundClick() {
        if (!this.canCompound) {
          uni.showToast({
            title: '请先集齐财神卡',
            icon: 'none',
            duration: 2000,
          });
          return;
        }

        if (!(await this.toCompound())) return;

        this.card.compound = true;
        const timer = setTimeout(() => {
          clearTimeout(timer);
          // 迟0.5秒开始执行移动动画
          this.card.translateX = true;
        }, 500);
        const timer1 = setTimeout(() => {
          clearTimeout(timer1);
          // 动画结束时的操作
          this.card.list.forEach((item, index) => {
            if (index > 0) {
              item.num--;
            } else {
              item.num++;
            }
          });
          this.card.compound = false;
          this.card.translateX = false;
        }, 1500);
      },

      /**
       * 合成请求
       */
      async toCompound() {
        Utils.Msg.ShowLoading();
        try {
          const { data: res } = await Api.index.composeCard({ time: new Date().getTime() });
          Utils.Msg.HideLoading();
          return true;
        } catch (error) {
          Utils.Msg.HideLoading();
          return false;
        }
      },

      toReadTask(e) {
        this.$refs.readTaskRef.close();
      },

      // 跳转个人卡包
      toMyCard() {
        h5uni.navigateTo({
          url: `/pages/webview/index?url=https://wap2.wxls.pro/coupon/?time=${new Date().getTime()}#/pages/coupon/myCoupon?commodityType=${
            this.config.configJson.config.myCard.commodityType
          }`, // 跳转个人卡包
        });
      },
      navTo(url) {
        if (!url) return;
        Utils.util.navTo(url);
      },
      noAct() {},
      // 判断是否登录
      checkLogin() {
        return Utils.util.checkAppLogin({
          options: this.options,
          url: 'pages/index/index',
          isCurrentPage: true,
        });
      },
      // 页面初始化
      initLoad() {
        const config = this.$store.state.config;
        try {
          this.share = {
            strShareId: config.code,
            strClassId: 'wxlsvote',
            strClassName: config.shareTitle,
            title: config.shareTitle,
            thumb: config.sharePicture,
            summary: config.shareDescribe,
            url: `${config.jumpAddress}?time=${new Date().getTime()}`,
          };
          // console.log('this.share---',JSON.stringify(this.share));
          Utils.appInteractionH5.init.init(this.options, this.share);
        } catch (e) {
          console.log('e---', e);
        }
      },
    },
  };
</script>

<style lang="scss" scoped>
  .content {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 10rem;
    height: 100%;
    min-height: 100vh;
    background-color: #630a0e;
    overflow: hidden;
    position: relative;
  }

  .bg-img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: auto;
    // z-index: -1;
  }

  .top-logo {
    position: absolute;
    top: 16rpx;
    left: 18rpx;
    width: 140rpx;
    height: 53rpx;
  }

  .top-title-info {
    position: absolute;
    top: 76rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #fff;
    .title {
      font-size: 42rpx;
      font-weight: 700;
      line-height: 1.75;
    }
    .info {
      font-size: 24rpx;
    }
  }

  .lottery-draw-flip {
    position: relative;
    width: 100%;
    height: 100%;

    .lottery-draw-text {
      position: absolute;
      top: 35%;
      left: 0;
      width: 100%;
      text-align: center;
      font-size: 50rpx;
      line-height: 1.75;
      color: #fff;
    }
    .lottery-draw-btn {
      position: absolute;
      top: 80%;
      left: 0;
      width: 100%;
      text-align: center;
      image {
        width: 50%;
      }
    }
  }

  .logo {
    width: 100%;
    height: 100%;
    cursor: pointer;
  }

  .lottery-draw-tip {
    width: 100%;
    margin-top: 30rpx;
    color: #fff;
    font-size: 32rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 1;
  }
  .my-card-btn {
    width: 40%;
    margin: 30rpx auto;
  }

  .card-num {
    font-size: 28rpx;
    color: #fff;
    margin: 10rpx auto;
    z-index: 1;
  }

  /******************************************************************/
  .flip_wrap {
    position: relative;
    display: inline-block;
    width: 636rpx;
    height: 850rpx;
    margin: 284rpx auto 22rpx;
    perspective: 800px; /*perspective属性定义3D元素距视图的距离,以像素计。该属性允许您改变 3D 元素查看 3D 元素的视图。*/
    box-sizing: border-box;
    z-index: 1;
  }
  .flip {
    width: 100%;
    height: 100%;
    // backface-visibility: hidden; /*背对屏幕时隐藏*/
    transition: all 1s ease; /*为翻牌添加过渡效果*/
    transform-style: preserve-3d; /*子元素将保留其 3D 位置。*/
  }
  .side {
    width: 100%;
    height: 100%;
    position: absolute; /*让背面和正面重叠*/
    left: 0;
    top: 0;
    font-size: 16px;
    color: #fff;
    text-align: center;
    z-index: 1;
  }
  .front {
    font-size: 18px;
  }
  .back {
    backface-visibility: hidden; /*背对屏幕时隐藏*/
    transform: rotateY(180deg);
    box-sizing: border-box;
    cursor: pointer;
  }
  .flip-active {
    transform: rotateY(-180deg);
  }

  /**********************************************/
  .translate-img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    transition: all 2s ease-out;
    z-index: 2;
  }
  .translate-active {
    /* transform: scale(0, 0) translateY(100vh); */
    animation: bounceOutDown var(--translateTime);
  }
  @keyframes bounceOutDown {
    0% {
      transform: translateY(0) scale(1, 1) rotateY(180deg);
    }

    20% {
      // opacity: 1;
      transform: translateY(-40rpx) scale(1.05, 1.05) rotateY(180deg);
    }

    100% {
      // opacity: 0;
      transform: translateY(900rpx) scale(0, 0) rotateY(180deg);
    }
  }

  /**********************************************/
  .card-wrap {
    position: relative;
    width: 100%;
    height: 296rpx;
    // padding: 20rpx 0;
    white-space: nowrap;
    box-sizing: content-box;
    overflow: scroll;
    z-index: 1;

    &::-webkit-scrollbar {
      display: none;
    }

    .card-content {
      position: relative;
      margin: 20rpx 0;
      height: 256rpx;
    }

    .card-item {
      position: relative;
      display: inline-block;
      width: 190rpx;
      height: 100%;
      margin: 0 18rpx;
      box-sizing: border-box;
      .card-item-img {
        width: 100%;
        height: 100%;
        border-radius: 12rpx;
      }
      .num-tag {
        position: absolute;
        top: -16rpx;
        right: -16rpx;
        width: 40rpx;
        height: 40rpx;
        background-color: #f8ddb6;
        border-radius: 50%;
        color: #fb4f19;
        font-size: 24rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1;
      }

      .view-bg {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba($color: #fff, $alpha: 0.4);
        border: 1px solid rgba($color: #fff, $alpha: 0.8);
        border-radius: 12rpx;
        transform: scale(1.05);
        z-index: -1;
      }
    }

    .compound-img-box {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      transition: all 1s ease;
      transform: translateX(0) scale(1.1, 1.1);
      z-index: 1;
    }
    .compound-img {
      width: 100%;
      height: 100%;
    }
  }
</style>
